package com.ly.mpayment.rest.up.shuoruan;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import com.sun.jersey.multipart.FormDataParam;
import org.apache.log4j.Logger;
import org.mortbay.util.MultiMap;
import org.mortbay.util.UrlEncoded;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

@Component
@Path("shuoruan")
public class ShouRuanRest {


    Logger logger = Logger.getLogger(ShouRuanRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;

    /**
     *
     *     public String callBack(@FormDataParam("order_id") String order_id, @FormDataParam("out_order_id") String out_order_id,
     *                            @FormDataParam("mchid") String mchid,
     *                            @FormDataParam("status") String status, @FormDataParam("tel") String tel, @FormDataParam("sign") String sign){
     * @return
     */
    @Path("callBack")
    @POST
//    @FormDataParam("Action") String Action,
//    @FormDataParam("AgentAccount") String AgentAccount,
//    @FormDataParam("Agentbalance") String Agentbalance,
//    @FormDataParam("Orderid") String Orderid,
//    @FormDataParam("Chargeid") String Chargeid,
//    @FormDataParam("Orderstatu_int") String Orderstatu_int,
//    @FormDataParam("Orderstatu_text") String Orderstatu_text,
//    @FormDataParam("OrderPayment") String OrderPayment,
//    @FormDataParam("Errorcode") String Errorcode,
//    @FormDataParam("Errormsg") String Errormsg,
//    @FormDataParam("Sign") String Sign
    public synchronized String callBack(@RequestBody String body){
        logger.info("shuoruan:"+body);
        if(!StringUtils.isBlank(body)){
            MultiMap multimap = Util.parceString(body);
            UpOrder order = upOrderService.findById(multimap.getString("Orderid"));
            if (order != null && (multimap.getString("Orderstatu_int").equals("11") || multimap.getString("Orderstatu_int").equals("16")) && order.getStatus() == Config.status[0]) {
                order.setRemark(multimap.containsKey("Chargeid") ? multimap.getString("Chargeid") : URLDecoder.decode(multimap.getString("Orderstatu_text")));
                RechargeRest.successUpOrder.add(order);
                return "OK";
//                20 取消处理 充值失败
//                21 处理失败 充值失败
//                26 缴费失败 充值失败
            }else if(order != null && order.getStatus() == Config.status[0] && (multimap.getString("Orderstatu_int").equals("20")
            || multimap.getString("Orderstatu_int").equals("26") || multimap.getString("Orderstatu_int").equals("21"))){
                order.setRemark( URLDecoder.decode(multimap.getString("Orderstatu_text")));
                RechargeRest.failtUpOrder.add(order);
                return "OK";
            }else{
                logger.info("shuoruan_not_found_order:" + multimap.getString("Orderid") +","+ (order == null ? " order is null" : order.getUpphonenum() ));
            }
        }
        return "failt";
    }

    private MultiMap parceString(String str){
        MultiMap map = new MultiMap();
        UrlEncoded.decodeTo(str, map, "utf-8");
        return map;
    }

    public void commitOrder(UpOrder order, UpShopInfo shop) {
        UpOrder product = this.upOrderService.findOrderProduct(order.getUporderuuid());
        if (product != null) {
            JSONObject data = new JSONObject();
            JSONObject body = new JSONObject();
            body.put("action","CZ");
            body.put("orderId",order.getUporderuuid());
            body.put("chargeAcct",order.getUpphonenum());
            body.put("chargeCash",product.getUpShopPro().getUpfacevalue());
            body.put("chargeType","0");
            body.put("retUrl",UrlEncoded.encodeString(shop.getOrderCallAddress()));

            //可填写：移动、联通、电信；
            //使用UrlEncode转码，采用UTF-8字符集
            //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
            //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
            //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
            body.put("ispName", URLEncoder.encode( order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "移动" :
                    order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "联通" :
                            order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "电信" : "xx"));
            data.put("agentAccount",shop.getAppId());
            data.put("sign",MD5.md5(body.toString()+shop.getUpkey()));
            data.put("busiBody",body);

            String res = HttpClient.post(shop.getOrderCommitAddress(),data.toString());
            logger.info("commitshuoruan_result:" + data +",phone:"+order.getUpphonenum()+",res:"+res);
            if (!StringUtils.isBlank(res)) {
                JSONObject result = JSONObject.parseObject(res);
                if(result.containsKey("errorCode") && result.getString("errorCode").equals("1")){
                    upOrderService.updateUpOrderMsg(order, result.getString("chargeId"),result.getString("errorDesc"));
                }else if (result.containsKey("errorCode") && codesError.contains(result.getString("errorCode"))) {
                    order.setRemark(result.containsKey("errorDesc") ?	result.getString("errorDesc") : Config.orderFailA);
                    RechargeRest.failtUpOrder.add(order);
                }
            } else {
                upOrderService.commitFailt(order,  Config.commitFailt);
                logger.info("commitshuoruan_error" + order.getUpphonenum());
            }
        }
    }

    /**
     * 提单错误直接失败
     */
    private static Set<String> codesError = new HashSet<String>(){{
        add("-100");
        add("-101");
        add("-102");
        add("-103");
        add("-200");
        add("-301");
        add("-302");
        add("-303");
        add("-304");
        add("-305");
        add("-310");
        add("-990");
        add("-991");
        add("-992");
        add("-999");
        add("-998");
    }};

    /**
     * @return
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        if(upOrder != null ){
            UpOrder product = upOrderService.findOrderProduct(upOrder.getUporderuuid());
            if (product != null) {
                JSONObject data = new JSONObject();
                JSONObject body = new JSONObject();
                body.put("action", "CX");
                body.put("orderId", upOrder.getUporderuuid());
                data.put("agentAccount", shopInfo.getAppId());
                data.put("sign", MD5.md5(body.toString() + shopInfo.getUpkey()));
                data.put("busiBody", body);
                String res = HttpClient.post(shopInfo.getOrderStatusAddress(), data.toString());
                logger.info("queryshuoruan:" + res + "data:" + data + ",phone:" + upOrder.getUpphonenum());
                if (res != null) {
                    JSONObject result = JSONObject.parseObject(res);
                    if (result.containsKey("errorCode") && result.getString("errorCode").equals("1")) {
                        if (result.getString("orderStatuInt").equals("11") ||
                                result.getString("orderStatuInt").equals("16")) {
                            UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
                            if (order != null && order != null && order.getStatus() == Config.status[0]) {
                                order.setRemark(result.containsKey("chargeId") ? result.getString("chargeId") : result.getString("orderStatuText"));
                                RechargeRest.successUpOrder.add(order);
                            }
                        } else if (result.getString("orderStatuInt").equals("20") ||
                                result.getString("orderStatuInt").equals("21") ||
                                result.getString("orderStatuInt").equals("26")) {
                            UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
                            if (order != null && order.getStatus() == Config.status[0]) {
                                order.setRemark(result.containsKey("orderStatuText") ? result.getString("orderStatuText") : result.getString("errorDesc"));
                                RechargeRest.failtUpOrder.add(order);
                            }
                        } else {
                            UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
                            upOrderService.addOrderMsg(order, result.getString("errorCode"));
                        }
                    } else {
                        logger.debug("queryshuoruan查询失败:" + upOrder.getUpphonenum());
                    }
                } else {
                    logger.info("queryshuoruan order failt:" + upOrder.getUpphonenum());
                }
            }
        }else{
            logger.info("queryshuoruan order failt:"+upOrder.getUpphonenum());
        }
    }

}
